/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package schedulerManagerment.Scheduler;

import Application.MarvellFrame;
import DataServices.LoadingBean;
import DataServices.TransactBean;
import connection.Configuration;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JTable;
import schedulerManagerment.company.CompanyManager;

/**
 *
 * @author DOANTUNGANH
 */
public class RequestHandlingForm extends javax.swing.JFrame implements MarvellFrame {

    LoadingBean loading = new LoadingBean();
    TransactBean transact = new TransactBean();
    // Connection conn to connect database
    public static Connection conn = null;
    private int selectedInterviewID;
    private Calendar dateScheduled = null;
    private Calendar selectedDeadLine = null;
    private boolean isDate = false;
//    Query used in request alert
    public String requestListTable_SQL = "SELECT A.ID,B.NAME AS SEEKER,CONVERT(VARCHAR(10),A.DATE,105)AS DATE,A.COMPANY,CASE A.RESULT WHEN 0 THEN 'Fail' WHEN 1 THEN 'Pass' END AS RESULT,CASE A.CHANGEREQUEST  WHEN  1 THEN 'Yes' WHEN 0 THEN 'No' END AS 'REQUEST',A.SALARY,A.SCHEDULER FROM ORINGINAL_SUB A INNER JOIN SEEKER B ON A.SEEKERID = B.ID WHERE A.CHANGEREQUEST = 1 AND (A.DATE >= GETDATE()) AND (RESULT IS NULL)";
    public String oringinalRequestListTable_SQL = "SELECT A.ID,B.NAME,A.DATE,A.COMPANY,CASE A.RESULT WHEN 0 THEN 'Fail' WHEN 1 THEN 'Pass' END AS RESULT,CASE A.CHANGEREQUEST  WHEN  1 THEN 'Yes' WHEN 0 THEN 'No' END AS 'REQUEST',A.SALARY,A.SCHEDULER FROM ORINGINAL_SUB A INNER JOIN SEEKER B ON A.SEEKERID = B.ID WHERE A.CHANGEREQUEST = 1 AND (A.DATE >= GETDATE()) AND (RESULT IS NULL)";
    public String deadLine_SQL = "SELECT V.DATEOFPOST FROM INTERVIEW I INNER JOIN VACANCY V ON I.VACANCYID = V.ID  WHERE I.ID = ";
    public String update_SQL = "UPDATE INTERVIEW SET DATE = ";

    /**
     * Creates new form RequestHandling
     */
    public RequestHandlingForm() {
        initComponents();
        loading.loadTable(requestListTable_SQL, requestListTable);
        jDateChooser.setVisible(false);
        changeBtn.setEnabled(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnBack = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        requestListTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jDateChooser = new com.toedter.calendar.JDateChooser();
        changeBtn = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        deadlineLbl = new javax.swing.JLabel();
        warningLbl = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/Import Document.png"))); // NOI18N
        btnBack.setText("back");
        btnBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBackActionPerformed(evt);
            }
        });

        requestListTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        requestListTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                requestListTableMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(requestListTable);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("List of interviews requested to change");

        jDateChooser.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jDateChooserPropertyChange(evt);
            }
        });

        changeBtn.setText("Update new date");
        changeBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeBtnActionPerformed(evt);
            }
        });

        jLabel2.setForeground(new java.awt.Color(255, 0, 0));
        jLabel2.setText("Dead Line : ");

        deadlineLbl.setForeground(new java.awt.Color(255, 0, 0));
        deadlineLbl.setText("                         ");

        warningLbl.setForeground(new java.awt.Color(255, 0, 0));
        warningLbl.setText("                ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 720, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnBack)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(deadlineLbl)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(changeBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(warningLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(22, 22, 22)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(deadlineLbl))
                    .addComponent(jDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addComponent(warningLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBack)
                    .addComponent(changeBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
        this.exitFrame();
    }//GEN-LAST:event_btnBackActionPerformed

    private void changeBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeBtnActionPerformed
        // TODO add your handling code here:
        configConnection();
        String sql = "{call UPDATEDAY(?,?)}";
        CallableStatement cs;
        try {
            cs = conn.prepareCall(sql);
            java.sql.Date sqlDateScheduled = new java.sql.Date(dateScheduled.getTime().getTime());
            cs.setDate(1, sqlDateScheduled);
            cs.setInt(2, selectedInterviewID);
            cs.execute();
        } catch (SQLException ex) {
            Logger.getLogger(ScheduleManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        loading.loadTable(requestListTable_SQL, requestListTable);
        warningLbl.setText("Update successfully");
    }//GEN-LAST:event_changeBtnActionPerformed

    private void requestListTableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_requestListTableMousePressed
        // TODO add your handling code here:
        int row = this.requestListTable.getSelectedRow();
        selectedInterviewID = (int) getCellObject(requestListTable, row, 0);
        System.out.println("selectedInterviewID = " + selectedInterviewID);
        JTable deadlineTbl = new JTable();
        loading.loadTable(deadLine_SQL + selectedInterviewID, deadlineTbl);
        Timestamp tempStamp = (Timestamp) getCellObject(deadlineTbl, 0, 0);
        System.out.println("Deadline get from database : " + tempStamp);
        selectedDeadLine = Calendar.getInstance();
        selectedDeadLine.setTime(tempStamp);
        deadlineLbl.setText(selectedDeadLine.get(Calendar.DAY_OF_MONTH) + "/" + (selectedDeadLine.get(Calendar.MONTH) + 1) + "/" + selectedDeadLine.get(Calendar.YEAR));
        JTable tempTbl = new JTable();
        loading.loadTable(oringinalRequestListTable_SQL, tempTbl);
        Calendar cal = Calendar.getInstance();
        Timestamp tstamp = (Timestamp) getCellObject(tempTbl, row, 2);
        cal.setTime(tstamp);
        dateScheduled = Calendar.getInstance();
        dateScheduled.setTime(tstamp);
        System.out.println("Selected date = " + cal.get(Calendar.DATE));
        jDateChooser.setVisible(true);
        jDateChooser.setCalendar(cal);
    }//GEN-LAST:event_requestListTableMousePressed

    private void jDateChooserPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jDateChooserPropertyChange
        // TODO add your handling code here:
        Calendar cal = this.jDateChooser.getCalendar();
        Calendar currentCal = Calendar.getInstance();
        if (dateScheduled != null) {
            if (cal.equals(dateScheduled)) {
                warningLbl.setText("You haven't change date");
                isDate = false;
            }
        }
        if ((cal != null) && (cal.after(currentCal)) && (cal.before(selectedDeadLine)) && !cal.equals(dateScheduled)) {
            dateScheduled = cal;
            warningLbl.setText("");
            isDate = true;
            System.out.println("right date");
        } else {
            warningLbl.setText("not selected or invalid date range");
            isDate = false;
        }

        if (isDate == false) {
            this.changeBtn.setEnabled(false);
        } else {
            this.changeBtn.setEnabled(true);
        }
    }//GEN-LAST:event_jDateChooserPropertyChange
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBack;
    private javax.swing.JButton changeBtn;
    private javax.swing.JLabel deadlineLbl;
    private com.toedter.calendar.JDateChooser jDateChooser;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable requestListTable;
    private javax.swing.JLabel warningLbl;
    // End of variables declaration//GEN-END:variables

    private Object getCellObject(JTable table, int row, int column) {
        return table.getModel().getValueAt(row, column);
    }

    @Override
    public void startFrame(JFrame app) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CompanyManager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        this.root = app;
        this.setVisible(true);
        root.setEnabled(false);
    }

    @Override
    public void exitFrame() {
        root.setEnabled(true);
        this.setVisible(false);
    }
    private JFrame root;
    
    
    // Config Connection
    private void configConnection() {
        Configuration createConn = new Configuration();
        conn = createConn.getConnect();
    }
}
